/*
 * The MIT License
 * 
 * Copyright (c) 2008 Comcast Interactive Media
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package cim.sf.core.command.equinox;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.InvalidSyntaxException;

import cim.sf.core.command.CommandInvocation;
import cim.sf.core.command.CommandNotFoundException;
import cim.sf.core.command.CommandShell;

/**
 * @author <a href="mailto:jeremy_volkman@cable.comcast.com">Jeremy Volkman</a>
 */
public class LegacyCommandProvider implements CommandProvider {

    private Activator activator;

    public LegacyCommandProvider(Activator activator) {
        this.activator = activator;
    }

    public String getHelp() {
        return "---New Console---\n\tnexec <command> [param [param...]] - Execute a new command\n";
    }
    
    public void _nexec(final CommandInterpreter ci) throws InvalidSyntaxException {
        CommandInterpreterOutputStream os = new CommandInterpreterOutputStream(ci);
        PrintStream ps = new PrintStream(os);

        String commandName = ci.nextArgument();
        if (commandName == null) {
            ci.println("No command specified");
            return;
        }
        
        CommandShell shell = (CommandShell) activator.shellTracker.getService();
        if (shell == null) {
            ci.println("No CommandShell available");
            return;
        }
        
        List<String> args = new ArrayList<String>();
        String arg;
        while ((arg = ci.nextArgument()) != null) {
            args.add(arg);
        }
        CommandInvocation cinv = new CommandInvocation(ps, ps, null, null, args.toArray(new String[args.size()]));

        try {
            shell.executeCommand(commandName, cinv);
        } catch (CommandNotFoundException e) {
            ci.println("Command not found: " + commandName);
        }
    }
    
    private static class CommandInterpreterOutputStream extends OutputStream {

        private static final String lineSeparator = System.getProperty("line.separator");
        private CommandInterpreter ci;
        private ByteArrayOutputStream os;
        
        public CommandInterpreterOutputStream(CommandInterpreter ci) {
            this.ci = ci;
            this.os = new ByteArrayOutputStream();
        }
        
        @Override
        public void write(int b) throws IOException {
            os.write(b);
            String str = os.toString();
            if (str.endsWith(lineSeparator)) {
                ci.print(str);
                os.reset();
            }
        }

        @Override
        public void close() throws IOException {
        }

        @Override
        public void flush() {
            ci.print(os.toString());
            os.reset();
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            for (int i = off; i < len; i++) {
                write(b[i]);
            }
        }

        @Override
        public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
        }
        
    }
}
